import React, { Component } from 'react';
import { Form, Input, message, Alert } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { getAccounts, setAccount } from '@api/user';
import validatorCreator from '@util/validator-creator';
import { PHONE_RE, EMAIL_RE } from '@util/constants';
import PasswordModal from './password-modal';
import { connect } from 'react-redux';
import './index.less';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const prefixCls = 'account-setting';

const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};

class AccountSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      password: '******',
      passwordModalVisible: false,
      userInfo: {},
      userRole: _.get(this.props, 'user.role'),
      isDefaultRole: false
    };
  }

  componentDidMount() {
    this.getAccoruntsData();
  }

  //获取账号设置页面数据
  getAccoruntsData = () => {
    getAccounts().then(res => {
      const data = res.data.data.data;
      this.setState({ isDefaultRole: _.get(data, 'isDefaultRole', false) });
      const userInfo = {
        nickname: _.get(data, 'staffOid.nickname', '') || _.get(data, 'nickname', ''),
        phone: _.get(data, 'staffOid.telephone', ''),
        email: _.get(data, 'staffOid.email', '') || _.get(data, 'email', ''),
        province: _.get(data, 'province', ''),
        city: _.get(data, 'city', ''),
        area: _.get(data, 'area', ''),
        openSiteRange: _.get(data, 'openSiteRange', false),
        siteRanges: _.get(data, 'siteRangeOid.siteRanges', [])
      };
      this.props.form.setFieldsValue({
        nickname: userInfo.nickname,
        phone: userInfo.phone.toString().replace(/(?=(\d{4})+$)/g, ' '),
        email: userInfo.email,
        location: { province: userInfo.province, city: userInfo.city, area: userInfo.area }
      });
      this.setState({
        userInfo
      });
    });
  };

  changePasswordModalVisible = (visible = false) => {
    this.setState({ passwordModalVisible: visible });
  };

  renderPhone() {
    if (!this.state.isDefaultRole) {
      return true;
    }
    return false;
  }

  renderEmail() {
    if (this.state.userRole === '审计员' || this.state.userRole === '系统管理员') {
      return false;
    }
    return true;
  }

  onClickSubmit = type => {
    const {
      form: { validateFields }
    } = this.props;
    const userInfo = _.cloneDeep(this.state.userInfo);
    validateFields([type], (err, values) => {
      if (err && err[type]) {
        return;
      }
      let body = {};
      if (type === 'location') {
        const { province, city, area } = values.location || {};
        userInfo['province'] = province;
        userInfo['city'] = city;
        userInfo['area'] = area;
        body = _.pick(userInfo, ['province', 'city', 'area']);
      } else if (type === 'phone') {
        userInfo[type] = _.get(values, type, '').replace(/\s/g, '');
        body[type] = userInfo[type];
      } else {
        userInfo[type] = _.get(values, type, '');
        body[type] = _.get(values, type, '');
      }

      this.setState({ loading: true });
      setAccount(body)
        .then(() => {
          message.success('修改成功');
          this.setState({ loading: false, userInfo });
        })
        .catch(() => {
          message.error('修改失败');
          this.setState({ loading: false });
        });
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      user
    } = this.props;
    const { password, passwordModalVisible, isDefaultRole, userRole } = this.state;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-title`}>账号设置</div>
        <div className={`${prefixCls}-form`}>
          <Form labelAlign="left" width={800}>
            <FormItem {...formItemLayout} key="area" label={'姓 名'} colon={false}>
              {getFieldDecorator('nickname', {
                rules: [
                  {
                    validator: validatorCreator('姓名', {
                      required: true,
                      min: 2
                    })
                  }
                ]
              })(<Input width={200} disabled={isDefaultRole} placeholder="请输入姓名" />)}
              <span
                className={`${prefixCls}-form-item-span be-color ${
                  isDefaultRole ? 'disabled-btn' : ''
                }`}
                onClick={() => !isDefaultRole && this.onClickSubmit('nickname')}
              >
                保存
              </span>
            </FormItem>
            {this.renderPhone() && (
              <FormItem {...formItemLayout} key="phone" label="手机号" colon={false}>
                {getFieldDecorator('phone', {
                  rules: [
                    {
                      validator: validatorCreator('手机号', {
                        reg: PHONE_RE
                      })
                    }
                  ]
                })(<Input width={200} placeholder="请输入手机号" disabled={isDefaultRole} />)}
                <span
                  className={`${prefixCls}-form-item-span be-color ${
                    isDefaultRole ? 'disabled-btn' : ''
                  }`}
                  onClick={() => !isDefaultRole && this.onClickSubmit('phone')}
                >
                  保存
                </span>
              </FormItem>
            )}
            {this.renderEmail() && (
              <FormItem {...formItemLayout} key="email" label="邮箱" colon={false}>
                {getFieldDecorator('email', {
                  rules: [
                    {
                      validator: validatorCreator('邮箱', {
                        reg: EMAIL_RE,
                        required: true
                      })
                    }
                  ]
                })(
                  <Input
                    width={200}
                    disabled={isDefaultRole && userRole !== '安全管理员'}
                    placeholder="请输入邮箱地址"
                  />
                )}
                <span
                  className={`${prefixCls}-form-item-span be-color ${
                    isDefaultRole && userRole !== '安全管理员' ? 'disabled-btn' : ''
                  }`}
                  onClick={() => userRole === '安全管理员' && this.onClickSubmit('email')}
                >
                  保存
                </span>
              </FormItem>
            )}
            <FormItem {...formItemLayout} key="password" label="密码" colon={false}>
              {password ? password : <span style={{ color: '#999ea8' }}>未设置</span>}
              <span
                className={`${prefixCls}-form-item-span be-color`}
                onClick={() => this.changePasswordModalVisible(true)}
              >
                修改
              </span>
            </FormItem>
            {user.role === '安全操作员' ? (
              <FormItem {...formItemLayout} label="资产管理范围" colon={false}>
                {this.state.userInfo.openSiteRange ? (
                  <TextArea
                    rows={4}
                    value={_.join(_.get(this.state.userInfo, 'siteRanges', []), '\n')}
                    placeholder={
                      '请输入标准格式IP，跳行隔开：\n10.10.10.2\n192.192.192.2\n2001:DB8:0:0:8:800:200C:417A'
                    }
                    disabled={true}
                  />
                ) : (
                  '不限制任何资产'
                )}
                <Alert
                  style={{ fontSize: 14 }}
                  message="该字段不可修改直接修改，请联系系统管理员或安全管理员进行修改"
                  type="warning"
                />
              </FormItem>
            ) : null}
          </Form>
        </div>
        <PasswordModal
          visible={passwordModalVisible}
          changePasswordModalVisible={visible => this.changePasswordModalVisible(visible)}
        />
      </div>
    );
  }
}

AccountSetting.propTypes = {
  form: PropTypes.object.isRequired,
  user: PropTypes
};

const mapStateToProps = state => {
  return {
    user: _.get(state, 'auth.user', {})
  };
};
export default connect(mapStateToProps)(Form.create()(AccountSetting));
